/** When.java.

	Purpose:
		
	Description:
		
	History:
		12:48:43 PM Oct 22, 2014, Created by jumperchen

Copyright (C) 2014 Potix Corporation. All Rights Reserved.
*/
package org.zkoss.zuti.zul;

import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.UiException;

/**
 * A <tt>when</tt> tag is used for <tt>choose</tt> like a Java <tt>switch</tt>
 * statement in that it lets you between a number of alternatives.
 * @author jumperchen
 * @since 8.0.0
 */
public class When extends If {

	private static final long serialVersionUID = 2014102212484302L;

	public When() {
		_afterComposed = true; // cannot be created by afterCompose, but Choose shadow element.
	}

	public Object setAttribute(String name, Object value) {
		if (BINDER.equals(name)) {
			getParent().setAttribute(name, value);
		}
		return super.setAttribute(name, value);
	}

	@Override
	public Object removeAttribute(String name) {
		Object result = super.removeAttribute(name);

		// if parent is null, it means the instance may be merged.
		if (BINDER.equals(name) && getParent() != null) {
			boolean hasAttr = false;
			for (Component child : getParent().getChildren()) {
				if (child.hasAttribute(name)) {
					hasAttr = true;
					break;
				}
			}
			if (!hasAttr)
				getParent().removeAttribute(name);
		}
		return result;
	}

	public void recreate() {
		if (isBindingReady()) { // MVVM
			Choose choose = (Choose) getParent();
			choose.compose(getShadowHost());
		} else {
			Choose choose = (Choose) getParent();
			if (choose != null) {
				choose.recreate();
			}
		}
	}

	protected void recreateDirectly() {
		super.recreate();
	}

	public void beforeParentChanged(Component parent) {
		if (parent != null && !(parent instanceof Choose))
			throw new UiException("Unsupported parent for otherwise: " + parent);
		super.beforeParentChanged(parent);
	}
}
